package com.augurit.gzcgwsp.lhsp.web;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import net.sf.json.JSONArray;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;


public class ProcessInstanceClient{
	private static Logger log=Logger.getLogger(ProcessInstanceClient.class);
	private String targetEndpointAddress = "http://172.17.240.93/BLSP/WebService/WebService.asmx";
	
	/**
	 * 接口一：办理进度公开接口
	 * InstanceID	工程编号
	 * DepID	部门编号（备注如：市发改委-SFGW），详见部门编号对照表
	 * 根据项目立案编号及部门编号获取当前步骤及属性
	 * @return 返回xml，解析
	 */
	public String GetProjectStep(String InstanceID,String DepID) throws Exception{

		String result="";
		try {
			Service service = new Service();
			String namespace = "http://tempuri.org/";
			String actionUri = "GetProjectStep"; //Action路径
			String op = "GetProjectStep"; //要调用的方法名
			Call call = (Call) service.createCall();
			call.setTargetEndpointAddress(new java.net.URL(targetEndpointAddress));
			call.setSOAPActionURI(namespace + actionUri); // action uri
			call.setOperationName(new QName(namespace, op));// 设置要调用哪个方法
			call.addParameter( new QName(namespace, "ID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
			call.addParameter( new QName(namespace, "depID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
			call.setReturnType(org.apache.axis.Constants.XSD_STRING);
			result =(String) call.invoke( new Object[] {InstanceID,DepID});
		} catch (Exception e) {
			e.printStackTrace();
		}
		Document document = null;
    	document = DocumentHelper.parseText(result);
		Map<String,String> map = parseGetDF_OpinionXML(document);		
		return Obj2String(map);
	}
	/**
	 * 接口二：工程信息共享接口
	 * 根据项目立案编号获取阶段一表制信息
	 * @return 返回xml，解析
	 */
	public String  GetProjectForm(String InstanceID) throws Exception{
			String result="";
			try {
				Service service = new Service();
				String namespace = "http://tempuri.org/";
				String actionUri = "GetProjectForm"; //Action路径
				String op = "GetProjectForm"; //要调用的方法名
				Call call = (Call) service.createCall();
				call.setTargetEndpointAddress(new java.net.URL(targetEndpointAddress));
				call.setSOAPActionURI(namespace + actionUri); // action uri
				call.setOperationName(new QName(namespace, op));// 设置要调用哪个方法
				call.addParameter( new QName(namespace, "ID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.setReturnType(org.apache.axis.Constants.XSD_STRING);
				result =(String) call.invoke( new Object[] {InstanceID});
			} catch (Exception e) {
				e.printStackTrace();
			}
			Document document = null;
	    	document = DocumentHelper.parseText(result);
			Map<String,String> map = parseGetDF_OpinionXML(document);		
			return Obj2String(map);
	}
	
	/**
	 * 获取收件材料
	 * @param InstanceID
	 * @param ResourceType
	 * @param deptCode
	 * @return
	 * @throws Exception
	 */
	public String getSqcl(String InstanceID, String ResourceType, String deptCode) throws Exception{
		List<List<Map<String,String>>> list = new ArrayList<List<Map<String,String>>>();
		List<Map<String,String>> DianZList = GetResourcesObjectInfo(InstanceID, "DianZ", "CHENGGUANWEI");
		List<Map<String,String>> ZhiZList = GetResourcesObjectInfo(InstanceID, "ZhiZ", "CHENGGUANWEI");
		List<Map<String,String>> ZhengZList = GetResourcesObjectInfo(InstanceID, "ZhengZ", "CHENGGUANWEI");
		list.add(DianZList);
		list.add(ZhiZList);
		list.add(ZhengZList);
		return Obj2String(list);
	}
	
	/**
	 * 接口三：材料信息共享接口
	 * 获取材料的信息
	 * 例子地址格式：http://219.12.16.189/ResourcePUB.aspx?id=i1q3dasd349fhcasd20asdj
	 * @return  
	 */
	public List<Map<String,String>>  GetResourcesObjectInfo(String InstanceID, String ResourceType, String deptCode) throws Exception{
			String result="";
			try {
				Service service = new Service();
				String namespace = "http://tempuri.org/";
				String actionUri = "GetResourcesObjectInfo"; //Action路径
				String op = "GetResourcesObjectInfo"; //要调用的方法名
				Call call = (Call) service.createCall();
				call.setTargetEndpointAddress(new java.net.URL(targetEndpointAddress));
				call.setSOAPActionURI(namespace + actionUri); // action uri
				call.setOperationName(new QName(namespace, op));// 设置要调用哪个方法
				call.addParameter( new QName(namespace, "InstanceID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "ResourceType"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "deptCode"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.setReturnType(org.apache.axis.Constants.XSD_STRING);
				result =(String) call.invoke( new Object[] {InstanceID,ResourceType,deptCode});
			} catch (Exception e) {
				e.printStackTrace();
			}
			//result = "<?xml version='1.0' encoding='utf-8'?><root type='S' Reason='Success'><xDocuments><xFiles><xName>ResourceID</xName><xValue>b2c769c3-120d-46a3-a9e7-2b2472fd5ddc</xValue></xFiles><xFiles><xName>FileName</xName><xValue>占用挖掘城市道路人行道审批结果</xValue></xFiles><xFiles><xName>ResourceName</xName><xValue>复件 (1)附件1.doc</xValue></xFiles><xFiles><xName>ResourceType</xName><xValue>审批结果材料</xValue></xFiles><xFiles><xName>ResourcePath</xName><xValue>http://172.17.240.93/flexpaperdb/9ED9BF41C0621080BB2A4F1CDE09937478DDFE5D07CD2BA6.doc</xValue></xFiles><xFiles><xName>CreateDateTime</xName><xValue>2013/5/13 11:39:40</xValue></xFiles><xFiles><xName>Owner</xName><xValue>CHENGGUANWEI</xValue></xFiles><xFiles><xName>ItemName</xName><xValue>城市道路人行道及相关公共场地挖掘审批</xValue></xFiles></xDocuments><xDocuments><xFiles><xName>ResourceID</xName><xValue>b2c769c3-120d-46a3-a9e7-2b2472fd5ddc</xValue></xFiles><xFiles><xName>FileName</xName><xValue>占用挖掘城市道路人行道审批结果</xValue></xFiles><xFiles><xName>ResourceName</xName><xValue>121.jpg</xValue></xFiles><xFiles><xName>ResourceType</xName><xValue>审批结果材料</xValue></xFiles><xFiles><xName>ResourcePath</xName><xValue>http://172.17.240.93/flexpaperdb/5D42A4E21285BC1D.jpg</xValue></xFiles><xFiles><xName>CreateDateTime</xName><xValue>2013/5/13 16:32:53</xValue></xFiles><xFiles><xName>Owner</xName><xValue>CHENGGUANWEI</xValue></xFiles><xFiles><xName>ItemName</xName><xValue>城市道路人行道及相关公共场地挖掘审批</xValue></xFiles></xDocuments><xDocuments><xFiles><xName>ResourceID</xName><xValue>b2c769c3-120d-46a3-a9e7-2b2472fd5ddc</xValue></xFiles><xFiles><xName>FileName</xName><xValue>占用挖掘城市道路人行道审批结果结果结果结果结果</xValue></xFiles><xFiles><xName>ResourceName</xName><xValue>121.jpg</xValue></xFiles><xFiles><xName>ResourceType</xName><xValue>审批结果材料</xValue></xFiles><xFiles><xName>ResourcePath</xName><xValue>http://172.17.240.93/flexpaperdb/5D42A4E21285BC1D.jpg</xValue></xFiles><xFiles><xName>CreateDateTime</xName><xValue>2013/5/13 16:32:53</xValue></xFiles><xFiles><xName>Owner</xName><xValue>CHENGGUANWEI</xValue></xFiles><xFiles><xName>ItemName</xName><xValue>城市道路人行道及相关公共场地挖掘审批</xValue></xFiles></xDocuments></root>";
			Document document = null;
	    	document = DocumentHelper.parseText(result);
	    	System.out.println(ResourceType+" ========= "+document.asXML());
			List<Map<String,String>> list = parseGetResourcesObjectInfoXML(document);
			
			return list;
	}
	
	public List<Map<String,String>> RemoveDuplicateResourcesObjectInfo(List<Map<String,String>> resultList){
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Map<String,String> map = new HashMap<String,String>();
		if(resultList != null){
			for(int i = 0;i < resultList.size();i++){
				Map<String,String> resultMap = resultList.get(i);
				String ItemName = resultMap.get("resultMap");
				
				String key = "";
				String value = "";
				boolean flag = false;
				Set keys = map.keySet( );  
				if(keys != null) {  
					Iterator iterator = keys.iterator();  
					while(iterator.hasNext( )) {
						key = (String)iterator.next();  
						value = (String)map.get(key);
						if(value.equals(ItemName)){//如果有重复，则先拿出前面的数据map，把后面的数据加到前面的map里面
							Map<String,String> preMap = resultList.get(Integer.parseInt(key));//拿出前面的map
							flag = true;
						}
					}
				}
				if(flag == false){
					map.put(""+i, ItemName);
				}
				
//				list2.add(e)
			}
		}
		return list;
	}
	
	/**
	 * 接口四：更新办理状态接口
	 * 更新业务办理状态
	 * 
	 * @return  返回 xml字符串
	 */
	public String  UpdateFlowState(String InstanceID,String DepID,String State,String Opinion,String OpinionResult) throws Exception {
			String result="";
			try {
				Service service = new Service();
				String namespace = "http://tempuri.org/";
				String actionUri = "UpdateFlowState"; //Action路径
				String op = "UpdateFlowState"; //要调用的方法名
				Call call = (Call) service.createCall();
				call.setTargetEndpointAddress(new java.net.URL(targetEndpointAddress));
				call.setSOAPActionURI(namespace + actionUri); // action uri
				call.setOperationName(new QName(namespace, op));// 设置要调用哪个方法
				call.addParameter( new QName(namespace, "ID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "depID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "state"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "opinionDetail"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "opinionResult"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.setReturnType(org.apache.axis.Constants.XSD_STRING);
				result =(String) call.invoke( new Object[] {InstanceID,DepID,State,Opinion,OpinionResult});
			} catch (Exception e) {
				e.printStackTrace();
			}
	     return result;
	}
	
	/**
	 * 接口五：提交办理结果材料
	 * 
	 * 
	 * @return  返回 xml字符串
	 */
	public String  UploadFlowResult(String InstanceID,String DepID,String ResourceID, String ZJHPWBH,String ZJHPWMC,String ZJHPWYXQX) throws Exception {
			String result="";
			try {
				Service service = new Service();
				String namespace = "http://tempuri.org/";
				String actionUri = "UploadFlowResult"; //Action路径
				String op = "UploadFlowResult"; //要调用的方法名
				Call call = (Call) service.createCall();
				call.setTargetEndpointAddress(new java.net.URL(targetEndpointAddress));
				call.setSOAPActionURI(namespace + actionUri); // action uri
				call.setOperationName(new QName(namespace, op));// 设置要调用哪个方法
				call.addParameter( new QName(namespace, "ID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "depID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "resourceID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "ZJHPWBH"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "ZJHPWMC"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.addParameter( new QName(namespace, "ZJHPWYXQX"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.setReturnType(org.apache.axis.Constants.XSD_STRING);
				result =(String) call.invoke( new Object[] {InstanceID,DepID,ResourceID,ZJHPWBH,ZJHPWMC,ZJHPWYXQX});
			} catch (Exception e) {
				e.printStackTrace();
			}
	     return result;
	}
	
	/**
	 * 接口六：获取办理意见
	 * 根据项目立案编号及部门编号获取所有部门办理意见
	 * 
	 * @return  返回 xml字符串
	 */
	public String  GetDF_Opinion(String InstanceID) throws Exception{
			String result="";
			try {
				Service service = new Service();
				String namespace = "http://tempuri.org/";
				String actionUri = "GetDF_Opinion"; //Action路径
				String op = "GetDF_Opinion"; //要调用的方法名
				Call call = (Call) service.createCall();
				call.setTargetEndpointAddress(new java.net.URL(targetEndpointAddress));
				call.setSOAPActionURI(namespace + actionUri); // action uri
				call.setOperationName(new QName(namespace, op));// 设置要调用哪个方法
				call.addParameter( new QName(namespace, "InstanceID"), org.apache.axis.Constants.XSD_STRING, ParameterMode.IN);
				call.setReturnType(org.apache.axis.Constants.XSD_STRING);
				result =(String) call.invoke( new Object[] {InstanceID});
			} catch (Exception e) {
				e.printStackTrace();
			}
			System.out.println("result"+result);
			Document document = null;
	    	document = DocumentHelper.parseText(result);
//			Map<String,String> map = parseGetDF_OpinionXML(document);
	    	
	    	List<Map<String,String>> list = parseGetResourcesObjectInfoXML(document);
			
			return Obj2String(list);
	}
	
	public String Obj2String(Object obj){
		//转成JSONArray类型
		JSONArray json = JSONArray.fromObject(obj);
		System.out.println(json.toString());//
		return json.toString();
	}
	
	
	/**
	 * 解析接口六：获取办理意见GetDF_Opinion方法返回的xml
	 * @param document
	 */
	public Map<String,String> parseGetDF_OpinionXML(Document document){
		List attachmentList = document.selectNodes("//xDocuments/xFiles");
		String jsonStr = "";
		Map<String,String> map = new HashMap<String,String>();
		for (Iterator it = attachmentList.iterator(); it.hasNext();) {
			Element attachmentEle = (Element) it.next();			
			String mapKey = "";
			String mapValue = "";
			List fileNameList = (List) attachmentEle.elements("xName");
			String key = "";
			for (Iterator fileNameIt = fileNameList.iterator(); fileNameIt.hasNext();) {		
				Element fileNameEle = (Element) fileNameIt.next();
				key = fileNameEle.getText();
//				if("DeptName".equals(key)){
//					mapKey = "部门名称";
//				}else if("PersonName".equals(key)){
//					mapKey = "办理人姓名";
//				}else if("OpinionResult".equals(key)){
//					mapKey = "意见结果";
//				}else if("OpinionDetail".equals(key)){
//					mapKey = "意见详细";
//				}else if("OpinionTime".equals(key)){
//					mapKey = "发布时间";
//				}
				mapKey = key;
//				System.out.println("mapKey = " + mapKey);
			}
			List displayNameList = (List) attachmentEle.elements("xValue");		
			for (Iterator displayNameIt = displayNameList.iterator(); displayNameIt.hasNext();) {		
				Element displayNameEle = (Element) displayNameIt.next();
				mapValue = displayNameEle.getText();				
//				System.out.println("mapValue = " + displayName);
			}
			System.out.println(mapKey+" : "+mapValue);
			map.put(mapKey, mapValue);
		}
		return map;
	}
	
	/**
	 * 解析收件材料xml
	 * @param document
	 */
	public List<Map<String,String>> parseGetResourcesObjectInfoXML(Document document){
		List<Map<String,String>> list = new ArrayList<Map<String,String>>();
		Element messageElement = document.getRootElement();
        
        //获取root元素下的子元素
        Iterator<Element> oneLevelElementItor = messageElement.elementIterator();
        Map<String,String> map = null;
        
        while(oneLevelElementItor.hasNext()){
        	map = new HashMap<String,String>();
//        	System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            Element e1 = oneLevelElementItor.next();
//            System.out.println("root子元素："+e1.getName());
            //获取xDocuments元素下的子元素
            Iterator<Element> twoLevelElementItor = e1.elementIterator();
            while(twoLevelElementItor.hasNext()) {
                Element e2 = twoLevelElementItor.next();
//                System.out.println("xDocuments子元素："+e2.getName());
//                userAttrMap.put(e2.getName(), e2.getText());
                
                //获取xFiles下的子元素
                if("xFiles".equals(e2.getName())) {
                    Iterator<Element> threeLevelElementItor = e2.elementIterator();
                    List<String> keyValueList = new ArrayList<String>();
                    while(threeLevelElementItor.hasNext()) {
                        Element e3 = threeLevelElementItor.next();
//                        System.out.println("xFiles子元素："+e3.getName());
//                        System.out.println("e3.getName() = "+e3.getName()+"  ---------------  e3.getText() = "+e3.getText());
                        keyValueList.add(e3.getText());
                    }
                    map.put(keyValueList.get(0), keyValueList.get(1));
                }
            }
            list.add(map);
        }
        System.out.println("list.size() = "+list.size());
		return list;
	}
	
	/**
	 * 格式化xml
	 * @param document
	 * @param charset
	 * @return
	 */
	public  String formatXML(Document document, String charset) { 
        OutputFormat format = OutputFormat.createPrettyPrint(); 
        format.setEncoding(charset); 
        //format= OutputFormat.createCompactFormat();
        StringWriter sw = new StringWriter(); 
        XMLWriter xw = new XMLWriter(sw, format); 
        try { 
                xw.write(document); 
                xw.flush(); 
                xw.close(); 
        } catch (IOException e) { 
                log.error("格式化XML文档发生异常，请检查！" , e); 
        } 
        return sw.toString(); 
	}
	
	public void parseGetDF_OpinionXML2(Document document){
		List attachmentList = document.selectNodes("//attachments/attachment");
		Map<String,String> map = new HashMap<String,String>();
		for (Iterator it = attachmentList.iterator(); it.hasNext();) {
			Element attachmentEle = (Element) it.next();			
			String mapKey = "";
			String mapValue = "";
			List displayNameList = (List) attachmentEle.elements("displayName");		
			for (Iterator displayNameIt = displayNameList.iterator(); displayNameIt.hasNext();) {		
				Element displayNameEle = (Element) displayNameIt.next();
				String displayName = displayNameEle.getText();
		//		System.out.println("mapKey = " + displayName);
				mapKey = displayName;
			}
			List fileNameList = (List) attachmentEle.elements("key");
			String key = "";
			for (Iterator fileNameIt = fileNameList.iterator(); fileNameIt.hasNext();) {		
				Element fileNameEle = (Element) fileNameIt.next();
				key = fileNameEle.getText();
		//		System.out.println("mapValue = " + key);
				mapValue = key;
			}
			map.put(mapKey, mapValue);
		}
	}
	
//    public static void main(String[] args) throws Exception{
//    	String InstanceID = "GZ2020130019-4-001";
//    	ProcessInstanceClientService client=new ProcessInstanceClientService();
//    	String returnStr=client.GetResourcesObjectInfo(InstanceID, "DianZ", "CHENGGUANWEI");
//    	String returnZhiZStr=client.GetResourcesObjectInfo(InstanceID, "ZhiZ", "CHENGGUANWEI");
//    	String returnZhengZStr=client.GetResourcesObjectInfo(InstanceID, "ZhengZ", "CHENGGUANWEI");
//    	String returnStr=client.UpdateFlowState(InstanceID, "CHENGGUANWEI", "受理", "城管委同意受理该案件", "同意");
//    	String returnStr=client.GetProjectForm(InstanceID);
//    	String returnStr=client.UploadFlowResult(InstanceID, "CHENGGUANWEI", ResourceID, ZJHPWBH, ZJHPWMC, ZJHPWYXQX);
//    	Document document = null;
//    	document = DocumentHelper.parseText(returnStr);
//    	System.out.print("返回的XML = "+client.formatXML(document,"UTF-8"));
//    	client.parseGetResourcesObjectInfoXML(document);
//    	List list =  new ArrayList();
//    	Map map = new HashMap();
//    	map.put("aa", "bb");
//    	Map map2 = new HashMap();
//    	map2.put("cc", "dd");
//    	map.put("ee", map2);
//    	list.add(map);
//    	client.Obj2String(list);
//    }
}
